package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import com.qk.management.service.UserService;
import com.qk.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author MrZhao
 * @created 2025-10-07 18:15
 * @description 用户管理业务层实现类
 *
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMapper roleMapper;


    private static final String STATUS_NORMAL = "0";
    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    @Override
    public void add(User user) {
        // 参数校验： 工具类处理 hutool 工具类
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 补全数据
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 设置默认密码
        // 原始密码（明文密码）
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        // MD5算法对原始密码进行消息摘要处理得到字符串（密文密码）
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        // 插入
        userMapper.insert(user);
    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        // 参数校验 （无）
        // 开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        // 查询
        List<UserDO> result = userMapper.selectByPage(dto);
        for (UserDO userDO : result) {
            userDO.setPhone(DesensitizedUtil.mobilePhone(userDO.getPhone()));
        }
        Page<UserDO> page = (Page<UserDO>) result;
        // 结果封装返回
        return PageResult.<UserDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }


    @Override
    public void deleteUser(List<Integer> ids) {
        //添加校验
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if (!isNotEmpty) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        userMapper.DeleteUser(ids);
    }

    @Override
    public User getUserById(Integer id) {
        User user=userMapper.getUserById(id);
        return user;
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+"123").getBytes()));
        userMapper.updateUser(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        // 参数校验
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 查询用户 dto.getUsername()
        User user =userMapper.getUserByUsername(dto.getUsername());
        //参数校验 user
        if (ObjectUtils.isEmpty(user)){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        Integer status = user.getStatus();
        boolean equal1 = ObjectUtil.equal(status, STATUS_NORMAL);
        if (equal1){
           CommonException.throwCommonException(ParamEnum.LOGIN_USER_STATUS_ERROR);
        }

        // 密码校验
        String loginPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String  dbPassword = user.getPassword();
        boolean equal = ObjectUtil.equal(loginPassword, dbPassword);
        if (!equal){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }

        // 查询角色 获取user.getRoleId()
        Role role =roleService.selectById(user.getRoleId());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());

        return UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtil.generateToken(claims))
                .build();
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> selectRoleLabel(String roleLabel) {
        Role role = roleMapper.selectByLable(roleLabel);
        if (ObjectUtils.isEmpty(role)){
            throw new RuntimeException("角色不存在");
        }
        return userMapper.selectRoleLabel(role.getId());
    }

    @Override
    public List<User> selectDept(Integer deptId) {
        return userMapper.selectDept(deptId);
    }
}
